﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;
using System.IO;

[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined, //use clr serialization to serialize the intermediate result
    IsInvariantToNulls = true, //optimizer property
    IsInvariantToDuplicates = false, //optimizer property
    IsInvariantToOrder = false, //optimizer property
    MaxByteSize = 8000) //maximum size in bytes of persisted value
]

/*用户自定义的CLR聚合类中必须四个函数:
 * Init,Accumulate,Merge,Terminate。
 * Init用户初始化，Accumulate用来实现具体的聚合算法，
 * Merge用来执行每一次的聚合逻辑顺序，Terminate用来将聚合的结果返回。 */

public struct JoinStr2 : IBinarySerialize
{

    // 这是占位符成员字段
    private System.Text.StringBuilder _sb;

    public void Init()
    {
        // 在此处放置代码
        _sb = new StringBuilder();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="value"></param>
    /// <param name="p1">分隔符</param>
    public void Accumulate(SqlString value, char p1 = ',')
    {
        // 在此处放置代码
        if (!value.IsNull)
        {
            _sb.Append(value.Value + p1);
        }
    }

    public void Merge(JoinStr2 Group)
    {
        // 在此处放置代码
        if (_sb != null)
        {
            _sb.Append(Group._sb);
        }
    }

    public SqlString Terminate()
    {
        // 在此处放置代码
        string result = string.Empty;
        if (_sb != null && _sb.Length > 0)
        {
            result = _sb.ToString(0, _sb.Length - 1);
        }
        return new SqlString(result);
    }

    public void Read(System.IO.BinaryReader r)
    {
        _sb = new System.Text.StringBuilder(r.ReadString());
    }

    public void Write(System.IO.BinaryWriter w)
    {
        if (_sb != null)
        {
            w.Write(_sb.ToString());
        }
    }
}
